# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
from resources_base.module_base.basetools import md5
# ========= 导入数据的类 ============
from userweb.models import Account


def index(request):
    """打开主界面"""
    # 判断session中是否存储有默认的产线
    if not request.session.get('current_line'):
        request.session['current_line'] = 1

    # 返回页面
    return render(request, 'main/main.html')


def change_info(request):
    """修改个人信息"""
    # 接收传递的值
    rec = request.POST
    # 修改
    try:
        # 获取当前的对象
        current_obj = Account.objects.filter(loginid = rec.get('loginid')).first()
        # 修改
        current_obj.name = rec.get('name')
        current_obj.department = rec.get('department')
        current_obj.position = rec.get('position')
        current_obj.mobile = rec.get('mobile')
        current_obj.email = rec.get('email')
        # 修改edit_time
        current_obj.edit_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 修改session:
        request.session['user']['department'] = rec.get('department')
        request.session['user']['name'] = rec.get('name')
        request.session['user']['position'] = rec.get('position')
        request.session['user']['mobile'] = rec.get('mobile')
        request.session['user']['email'] = rec.get('email')
        request.session['user']['edit_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 保存
        current_obj.save()
        # 返回
        return JsonResponse({'status': True,})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '修改个人信息提交到数据库出现异常，具体原因：' + str(e)})


def change_pwd(request):
    """修改密码"""
    # 获取数据
    rec = request.POST
    # 判断旧密码是否正确
    account_obj = Account.objects.filter(loginid=rec.get('ch_loginid'), loginpwd=md5(rec.get('oldpwd'))).first()
    if not account_obj:
        return JsonResponse({'status': False, 'error': '原密码错误！'})
    # 开始修改
    try:
        # 获取当前的对象
        account_obj.loginpwd = md5(rec.get('loginpwd'))
        # 修改edit_time
        account_obj.edit_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 保存
        account_obj.save()
        # 返回
        return JsonResponse({'status': True,})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '修改密码提交到数据库出现异常，具体原因：' + str(e)})


def flush_login(request):
    """注销"""
    request.session.flush()
    # 跳转到登录页面
    return redirect(reverse('login'))